fetch("http://localhost:7010/chat", {
  method: "post",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    clear: true,
  }),
});

const formEl = document.querySelector("form");
const textAreaEl = document.querySelector("textarea");

textAreaEl.onkeydown = (e) => {
  if (e.key === "Enter" && !e.shiftKey && !e.ctrlKey && !e.altKey) {
    e.preventDefault();
    formEl.dispatchEvent(new Event("submit"));
  }
};

formEl.onsubmit = async (e) => {
  e.preventDefault();
  const content = textAreaEl.value;
  createUserContent("袁");
  const robot = createRobotContent("机器人");

  const resp = await fetch("http://localhost:7010/chat", {
    method: "post",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      content,
    }),
  });

  // 流式读取
  const reader = resp.body.getReader();
  const decoder = new TextDecoder();
  while (1) {
    const { done, value } = await reader.read();
    if (done) {
      break;
    }
    const txt = decoder.decode(value);
    robot.apppend(txt);
  }
  robot.over(txt);

  /* const body = await resp.text();
  robot.append(body);
  robot.over(); */
};
